package com.itheima.reggie.controller.backend;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.Result;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.entity.OrdersExport;
import com.itheima.reggie.service.OrderService;
import com.itheima.reggie.util.IpUtil;
import com.itheima.reggie.util.LoginUserUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

/**
 * 订单
 */
@Slf4j
@RestController
@RequestMapping("/backends/order")
public class OrderController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private LoginUserUtil loginUserUtil;

    /**
     * 用户下单
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public Result<String> submit(@RequestBody Orders orders){
        Object user = loginUserUtil.getBackendUser();

        log.info("订单数据：{}",orders);
        orderService.submit(orders,Long.parseLong(user.toString()));
        return Result.success("下单成功");
    }

    /**
     * 查询用户所有下单，分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public Result<Page> page(Integer page, Integer pageSize){

        Object user = loginUserUtil.getBackendUser();
        //分页构造器
        Page<Orders> pageInfo = new Page<Orders>((page-1)*pageSize,pageSize);
        //条件构造器
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId, Long.parseLong(user.toString()));
        //添加排序条件，根据sort进行排序
        queryWrapper.orderByDesc(Orders::getOrderTime);
        //分页查询
        orderService.page(pageInfo,queryWrapper);
        return Result.success(pageInfo);
    }

    /**
     * 订单分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public Result<Page> page(Integer page, Integer pageSize,String number,String beginTime,String endTime){
        //分页构造器
        Page<Orders> pageInfo = new Page<Orders>((page-1)*pageSize,pageSize);
        //条件构造器
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        if(StringUtils.isNotEmpty(number)) {
            queryWrapper.eq(Orders::getNumber, number);
        }

        if(StringUtils.isNotEmpty(beginTime)){
            queryWrapper.gt(Orders::getOrderTime, beginTime);
        }

        if(StringUtils.isNotEmpty(beginTime)){
            queryWrapper.lt(Orders::getOrderTime, endTime);
        }

        //添加排序条件，根据sort进行排序
        queryWrapper.orderByDesc(Orders::getOrderTime);
        //分页查询
        orderService.page(pageInfo,queryWrapper);
        return Result.success(pageInfo);
    }


    /**
     * 导出数据
     * @param response
     */
    @SneakyThrows(IOException.class)
    @GetMapping(value = "/export")
    public void exportJobPojoList(HttpServletResponse response) {
        setExcelRespProp(response, "订单明细");
        List<OrdersExport> ordersExports = orderService.selectToExport();
        EasyExcel.write(response.getOutputStream())
                .head(OrdersExport.class)
                .excelType(ExcelTypeEnum.XLSX)
                .sheet("订单明细")
                .doWrite(ordersExports);
    }

    /**
     * 设置excel下载响应头属性
     */
    private void setExcelRespProp(HttpServletResponse response, String rawFileName) throws UnsupportedEncodingException {
        //response.setContentType("multipart/form-data");

        response.setContentType(
                "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode(rawFileName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
    }

}